package cn.edu.scnu.thewonderofink.logic.network

import android.util.Log
import androidx.lifecycle.ViewModelProvider
import cn.edu.scnu.thewonderofink.logic.model.RecognitionResponse
import cn.edu.scnu.thewonderofink.ui.home.HomeViewModel
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import org.json.JSONObject


class MyWebSocketListener : WebSocketListener() {

    /**
     * @说明 连接成功时回调
     */
    override fun onOpen(webSocket: WebSocket, response: Response) {
        super.onOpen(webSocket, response)
    }

    /**
     * @说明 收到消息时回调
     */
    override fun onMessage(webSocket: WebSocket, text: String) {
        super.onMessage(webSocket, text)
        Log.d("Testing", "Approaching onMessage")
        val json = JSONObject(text)
        val recognitionResponse = RecognitionResponse(
            json.getString("code"),
            json.getString("message"),
            json.getString("char"),
            json.getString("score")
        )
        RecognitionNetwork.setResponse(recognitionResponse)
    }

    /**
     * @说明 连接关闭时回调
     */
    override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
        super.onClosed(webSocket, code, reason)
        Log.d("Testing", "Approaching onClosed")
    }

    /**
     * @说明 连接失败时回调
     */
    override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
        super.onFailure(webSocket, t, response)
        Log.d("Testing", "Approaching onFailure")
        webSocket.close(1000, "连接失败")
    }
}